import { Badge, Button, message, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import $utils from '@/utils/utils';

import { getHealthList, getHealthStationNames } from '@/services/health';
import { codeColorData, hasPositiveData, healthLabelData, nucleinAcidStatusData, vaccineStatusData } from '@/utils/common';

const initDate = {};

const HealthList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);

    const [stationNames, setStationNames] = useState<API.Select[]>([]);


    const l_state: any = history.location.state;
    useEffect(() => {
        const getStationNames = async () => {
            try {
                const msg = await getHealthStationNames({});
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.map((item: string) => {
                        new_data.push({
                            label: item,
                            value: item,
                        });
                    });
                    setStationNames(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
                message.error('校园小区列表获取失败!');
            }
        };

        getStationNames()

        if (!initParams) {
            const data = {
                ...l_state,
                ...initDate,
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        const data = {
            ...initDate,
        }
        if (JSON.stringify(initParams) === JSON.stringify(data)) {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    const columns: ProColumns<any>[] = [
        {
            title: '打卡时间',
            dataIndex: 'createTime',
            hideInTable: true,
            valueType: 'dateTimeRange',
            search: {
                transform: (value: any) => ({ startDate: value[0], endDate: value[1] }),
            },
            width: '120px',
            order: 5,
        },
        {
            title: '姓名',
            dataIndex: 'name',
            order: 3,
            render: (dom, entity) => {
                return (
                    entity.isAbnormal === 1 ? <Badge.Ribbon style={{ left: '-14px', top: '-16px' }} color={'volcano'} placement="start" text="异常">
                        {dom}
                    </Badge.Ribbon> : <div>{dom}</div>
                )
            }
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            order: 2,
        },
        {
            title: '校园小区',
            dataIndex: 'stationName',
            valueType: 'select',
            order: 4,
            fieldProps: {
                showSearch: true,
                options: stationNames
            }
        },
        {
            title: '健康状况',
            dataIndex: 'label',
            valueType: 'select',
            search: false,
            fieldProps: {
                options: healthLabelData,
            }
        },
        {
            title: '健康码颜色',
            dataIndex: 'codeColor',
            valueType: 'select',
            search: false,
            fieldProps: {
                options: codeColorData,
            }
        },
        {
            title: '核酸状态',
            dataIndex: 'nucleinAcidStatus',
            valueType: 'select',
            search: false,
            fieldProps: {
                options: nucleinAcidStatusData,
            }
        },
        {
            title: '疫苗接种情况',
            dataIndex: 'vaccineStatus',
            valueType: 'select',
            search: false,
            fieldProps: {
                options: vaccineStatusData,
            }
        },
        {
            title: '是否异常',
            dataIndex: 'isAbnormal',
            valueType: 'select',
            hideInTable: true,
            fieldProps: {
                options: hasPositiveData,
            }
        },
        {
            title: '打卡时间',
            dataIndex: 'createTime',
            hideInForm: true,
            search: false,
            width: '120px',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Access accessible={true}>
                        <Button type="primary" size="small" onClick={() => {
                            const newTab = {
                                name: `打卡详情`,
                                path: '/OperationsMange/Health/detail',
                                state: {
                                    status: 'detail',
                                    data: record
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/OperationsMange/Health/detail',
                                state: {
                                    status: 'detail',
                                    data: record
                                }
                            });
                        }}>详情</Button>
                    </Access>
                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                formRef={formRef}
                form={{
                    initialValues: initParams
                }}
                search={true ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 8,
                    },
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                const data = {
                                    ...initDate,
                                };
                                setParams(data);
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                options={false}
                request={async (params: any) => {
                    const msg = await getHealthList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '健康打卡',
                            path: '/OperationsMange/Health',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.data || [],
                        success: msg.code === 0,
                        total: msg.body?.total,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default HealthList;
